package b1.scenes.home
{
	import b1.conifg.*;
	import b1.controls.basic.*;
	import b1.net.*;
	import b1.players.*;
	import b1.scenes.*;
	import b1.scenes.fight.*;
	import b1.utils.*;
	import b1.conifg.story.FightConfig;
	
	import com.greensock.TweenLite;
	import com.greensock.easing.Expo;
	
	import flash.display.Sprite;
	import flash.events.*;
	import flash.text.*;

	public class ArrestWarrantDialog extends Sprite
	{
		private var type:int;
		private var detectiveAnimal:AnimalInfo;
		private var arrestTagertAnimal:AnimalInfo;
		private var battleCase:BattleCaseInfo;
		private var battleCases:Array;
		private var claimBones:int;
		private var wantedBonesSum:int;
    	private var leftButton:BasicButton;
    	private var rightButton:BasicButton;
    	private var refjectFlag:Boolean;
    	private const itemGap:int = 30;
		
		//type: 0, 探案某个案件；1, 探案通缉犯 
		public function ArrestWarrantDialog(detectiveAnimal:AnimalInfo, arrestTagertAnimal:AnimalInfo, refjectFlag:Boolean, claimBones:int, type:int, battleCase:BattleCaseInfo, wantedBonesSum:int, battleCases:Array)
		{
			super();
			this.type = type;
			this.detectiveAnimal = detectiveAnimal;
			this.arrestTagertAnimal = arrestTagertAnimal;
			this.battleCases = battleCases;
			this.battleCase = battleCase;
			this.claimBones = claimBones;
			this.wantedBonesSum = wantedBonesSum;
			this.refjectFlag = refjectFlag;
			
			//逮捕令对话框
			var ArrestDialogBgr:Class = ResourceHelper.getInstance().getClassByName("ArrestDialogBgr");
			var dialogSprite:Sprite = new ArrestDialogBgr();
			addChild(dialogSprite);
			
			//动物头像框
			var animalRect:Sprite = new Sprite();
			animalRect.graphics.lineStyle(2, 0x000000);
			animalRect.graphics.beginFill(0xFFFFFF);
			animalRect.graphics.drawRoundRect(0, 0, 100, 100, 15, 15);
			animalRect.graphics.endFill();
			animalRect.x = 50;
			animalRect.y = 140;
			addChild(animalRect);
			
			//动物头像遮罩
			var animalRectMask:Sprite = new Sprite();
			animalRectMask.graphics.lineStyle(2, 0x000000);
			animalRectMask.graphics.beginFill(0xFFFFFF);
			animalRectMask.graphics.drawRoundRect(0, 0, 100, 100, 15, 15);
			animalRectMask.graphics.endFill();
			animalRectMask.x = animalRect.x;
			animalRectMask.y = animalRect.y;
			addChild(animalRectMask);
			
			//动物头像
			var animalMc:AnimalMc = new AnimalMc(arrestTagertAnimal.id, 100);
			animalMc.x = 100;
			animalMc.y = 260;
			animalMc.mask = animalRectMask;
			addChild(animalMc);

			//标题名字
			var animalName:TextField = BFont.getAnimalFullName(arrestTagertAnimal);
			animalName.x = 170;
			animalName.y = 130;
			addChild(animalName);
			var titleText:TextField = new TextField();
			titleText.wordWrap = true;
			titleText.selectable = false;
        	titleText.autoSize = TextFieldAutoSize.LEFT;
			titleText.defaultTextFormat = new TextFormat("微软雅黑", 15, 0x000000);
			titleText.width = 100;
			titleText.x = 170;
			titleText.y = animalName.y + 20;
			var showBones:int;
			if (refjectFlag)
			{
				if (type == 0)
				{
					titleText.text = "不是该案的罪犯。对方要求赔偿骨头";
				}
				else
				{
					titleText.text = "不是通缉犯。对方要求赔偿骨头";
				}
				showBones = claimBones;
			}
			else
			{
				if (type == 0)
				{
					if(battleCase.loseHeirloomId > 0 ) titleText.text = "正是作案的真凶。奖励";
					else titleText.text = "正是作案的真凶。奖励";
					var victimAnimal:AnimalInfo = PlayerInfoHelper.getInstance().animals[this.battleCase.loserAnimalId];
					showBones = battleCase.caseBones * detectiveAnimal.intelligence / (victimAnimal.intelligence + detectiveAnimal.intelligence);
				}
				else
				{
					titleText.text = "正是在逃的通缉犯。通缉奖励";
					showBones = wantedBonesSum;
				}
			}
			this.addChild(titleText);
			var rewardItemStartY:int = titleText.y + titleText.height + 10;
		
			
			//结算经验
			var addExp:int;
			if (type == 0)
			{
				addExp = battleCase.caseBones * Config.expPerCaseBone;
			}
			else
			{
				var caseBones:int = 0;
				for (var i:int = 0; i < this.battleCases.length; i++)
				{
					var battleCase:BattleCaseInfo = this.battleCases[i];
					caseBones += battleCase.caseBones;
				}
				caseBones *= Config.compensationRaioForRunAway;
				addExp = caseBones * Config.expPerCaseBone; 
			}
			
			if (battleCase != null && battleCase.loseHeirloomId > 0)
			{
				//加载传家骨
				addRewardItem(170, rewardItemStartY, "传家骨", "Heirloom", "1");
				//骨头
				addRewardItem(170, rewardItemStartY + 25, "骨头", "PriceBone", showBones.toString());
				//经验
				if (!refjectFlag)
					addRewardItem(170, rewardItemStartY + 50, "经验", "ExpIcon", addExp.toString());
			}
			else if (battleCase != null)
			{
				addRewardItem(170, rewardItemStartY, "骨头", "PriceBone", showBones.toString());
				//经验
				if (!refjectFlag)
					addRewardItem(170, rewardItemStartY + 25, "经验", "ExpIcon", addExp.toString());
			}
			
			//按钮
			var ButtonBgr1:Class = ResourceHelper.getInstance().getClassByName("ButtonBgr1");
			var buttonTxt:String;
			if (refjectFlag)
			{
				buttonTxt = "反抗";
			}
			else
			{
				buttonTxt = "逮捕";	
			}
			leftButton = new BasicButton(ButtonBgr1, buttonTxt);
			leftButton.x = 50;
			leftButton.y = 290;
			leftButton.addEventListener(MouseEvent.CLICK, onLeftButtonClick);
			this.addChild(leftButton);
			
			if (refjectFlag)
			{
				buttonTxt = "算了";
			}
			else
			{
				buttonTxt = "算了";	
			}
			rightButton = new BasicButton(ButtonBgr1, buttonTxt);
			rightButton.x = leftButton.x + leftButton.width + 20;
			rightButton.y = leftButton.y;
			rightButton.addEventListener(MouseEvent.CLICK, onRightButtonClick);
			this.addChild(rightButton);

			//印章
			TweenLite.delayedCall(1, addStamp);
		}
		
		//奖励的每一项的信息
		private function addRewardItem(posX:int, posY:int, leftWords:String, iconStr:String, rightWords:String):void
		{
			var leftText:TextField = new TextField();
	    	leftText.autoSize = TextFieldAutoSize.LEFT;
	    	leftText.selectable = false;
			leftText.defaultTextFormat = new TextFormat("微软雅黑", 15, 0x000000);
			leftText.text = leftWords;
			leftText.x = posX;
			leftText.y = posY;
			addChild(leftText);
			var Icon:Class = ResourceHelper.getInstance().getClassByName(iconStr);
			var icon:Sprite = new Icon();
			icon.width = 20;
			icon.height = 20;
			icon.x = leftText.x + leftText.width + 5;
			icon.y = leftText.y +(leftText.height - icon.height) / 2;
			addChild(icon);
			var rightText:TextField = new TextField();
			rightText.selectable = false;
	    	rightText.autoSize = TextFieldAutoSize.LEFT;
			rightText.defaultTextFormat = new TextFormat("微软雅黑", 15, 0x000000);
			rightText.text = rightWords;
			rightText.x = icon.x + icon.width + 5;
			rightText.y = leftText.y;
			addChild(rightText);
		}

		private function getTextField(text:String, fontSize:int = 15):TextField
		{
			var textfield:TextField = new TextField();
			textfield.selectable = false;
        	textfield.autoSize = TextFieldAutoSize.LEFT;
			textfield.defaultTextFormat = new TextFormat("微软雅黑", fontSize, 0x000000);
			textfield.text = text;
			return textfield;
		}
		
		private function onLeftButtonClick(event:MouseEvent):void
		{
			//错误判断罪犯并反抗
			if (refjectFlag)
			{
				var players:Object = PlayerInfoHelper.getInstance().players;
				var leftPlayer:PlayerInfo = players[detectiveAnimal.ownerId];
				var rightPlayer:PlayerInfo = players[arrestTagertAnimal.ownerId];
				ServerHelper.getInstance().startFight(leftPlayer.id, rightPlayer.id, [detectiveAnimal.id], [arrestTagertAnimal.id], onStartFightComplete);
			}
			//正确判断罪犯并逮捕
			else
			{
				var secondsInPrison:int;
				var timeToGetFree:int;
				var victimAnimal:AnimalInfo;
				var victimBone:int;
				var detectiveBone:int;
				var boneBalance:String;
				var addExp:int;
				var expBalance:String;
				var heirloomBalance:String = new String();
				if (type == 0)
				{
					secondsInPrison = Math.max(Config.secondsInPrisonPerBone * this.battleCase.caseBones, Config.baseSecondsInPrison);
					timeToGetFree = Math.max(this.arrestTagertAnimal.timeToGetFree, ServerHelper.getInstance().now()) + secondsInPrison;
					victimAnimal = PlayerInfoHelper.getInstance().animals[this.battleCase.loserAnimalId];
					victimBone = battleCase.caseBones * victimAnimal.intelligence / (victimAnimal.intelligence + detectiveAnimal.intelligence);
					detectiveBone = battleCase.caseBones - victimBone;
					addExp = battleCase.caseBones * Config.expPerCaseBone;
					//结算骨头
					boneBalance = this.arrestTagertAnimal.ownerId + ",0," + (-battleCase.caseBones).toString() + "," + victimAnimal.ownerId + ",0," + victimBone +  
					"," + this.detectiveAnimal.ownerId + ",0," + detectiveBone;
					var levelExp:Array = AnimalInfo.getLevelByAddExp(this.detectiveAnimal.level, this.detectiveAnimal.experience, addExp);
					expBalance = this.detectiveAnimal.id + "," + levelExp[0] + "," + addExp + "," + Config.skillPointsPerLevel;
					if (battleCase.loseHeirloomId > 0) 
						heirloomBalance = battleCase.loseHeirloomId + "," + battleCase.loseHeirloomId + "," + PlayerInfoHelper.getInstance().userId + "," +battleCase.loseHeirloomId;
				}
				else
				{
					boneBalance = "";
					var caseBones:int = 0;
					for (var i:int = 0; i < this.battleCases.length; i++)
					{
						var battleCase:BattleCaseInfo = this.battleCases[i];
						caseBones += battleCase.caseBones;
						boneBalance += battleCase.loserOwnerId + ",0," + battleCase.caseBones + ",";
					}
					caseBones *= Config.compensationRaioForRunAway;
					addExp = caseBones * Config.expPerCaseBone; 
					secondsInPrison = Math.max(Config.secondsInPrisonPerBone * caseBones, Config.baseSecondsInPrison);
					timeToGetFree = Math.max(this.arrestTagertAnimal.timeToGetFree, ServerHelper.getInstance().now()) + secondsInPrison;
					boneBalance += this.arrestTagertAnimal.ownerId + ",0," + (-caseBones).toString() + "," + this.detectiveAnimal.ownerId + ",0," + this.wantedBonesSum;
					levelExp = AnimalInfo.getLevelByAddExp(this.detectiveAnimal.level, this.detectiveAnimal.experience, addExp);
					expBalance = this.detectiveAnimal.id + "," + levelExp[0] + "," + addExp + "," + Config.skillPointsPerLevel;
				}
				ServerHelper.getInstance().arrestAnimal(this.detectiveAnimal.id, this.arrestTagertAnimal.id, timeToGetFree, boneBalance, expBalance, heirloomBalance, onCompleteArrestAnimal);
			}
		}
		
		private function onStartFightComplete(result:String, leftPlayerId:int, rightPlayerId:int, leftAnimals:Array, rightAnimals:Array):void
		{
			//开始反抗，加载战斗画面
			if (result == "success")
			{
				var fight:Fight = new Fight(leftPlayerId, rightPlayerId, leftAnimals, rightAnimals, onEndFightComplete);
				SceneContainer.getInstance().loadScene(fight);
			}
			//对方还在上场战斗的冷却中
			else
			{
				var rightAnimalInfo:AnimalInfo = PlayerInfoHelper.getInstance().animals[rightAnimals[0]];
				var msgBox:MessageBox = new MessageBox(rightAnimalInfo.ownerName + " 的 " + rightAnimalInfo.animalName + " 还在上次战斗的恢复中……");
				msgBox.x = (BFont.stageWidth - msgBox.width) / 2;
				msgBox.y = (BFont.stageHeight - msgBox.height) / 2;
				var home:Home = SceneContainer.getInstance().currentScene as Home;
				home.addChild(msgBox);
			}
		}
		
		private function onEndFightComplete(leftPlayerId:int, rightPlayerId:int, winnerAnimalId:int, loserAnimalId:int, caseBones:int, loseHeirloomId:int, 
			animalCluesDrop:Object, fightConfig:FightConfig, newHonours:Object):void
		{
			close();
			var boneBalance:String;
			//如果反抗成功，逃过这次赔偿，但被立案
			if (winnerAnimalId == detectiveAnimal.id)
			{
				boneBalance = detectiveAnimal.ownerId + ",0," + this.claimBones;
				ServerHelper.getInstance().addCase(winnerAnimalId, loserAnimalId, caseBones, animalCluesDrop, boneBalance, loseHeirloomId, onAddCaseComplete);
			}
			//如果反抗失败，加倍处罚
			else
			{
				boneBalance = detectiveAnimal.ownerId + ",0," + (-this.claimBones);
				ServerHelper.getInstance().balance(null, boneBalance, null, onBalanceComplete); 
			}
		}
		
		private function onBalanceComplete(result:String):void
		{
			var msgBox:MessageBox = new MessageBox("反抗失败，加倍处罚！");
			msgBox.x = (BFont.stageWidth - msgBox.width) / 2;
			msgBox.y = (BFont.stageHeight - msgBox.height) / 2;
			var home:Home = SceneContainer.getInstance().currentScene as Home;
			home.addChild(msgBox);
		}
		
		private function onAddCaseComplete(result:String, battleCase:BattleCaseInfo):void
		{
			if (result == "success")
			{
				var caseEstablishDialog:CaseEstablishDialog = new CaseEstablishDialog(battleCase);
				var home:Home = SceneContainer.getInstance().currentScene as Home;
				caseEstablishDialog.x = BFont.stageWidth / 2;
				caseEstablishDialog.y = BFont.stageHeight / 2;
				home.addChild(caseEstablishDialog);
			}
		}
		
		private function onCompleteArrestAnimal(result:String):void
		{
			close();
			//播放逮捕动画
			var home:Home = SceneContainer.getInstance().currentScene as Home;
			home.startArrestAnimalMovie(arrestTagertAnimal.id);
			home.refreshHeirlooms();
		}
		
		private function onRightButtonClick(event:MouseEvent):void
		{
			//错误判断罪犯并服罪
			if (refjectFlag)
			{
				close();
			}
			//正确判断罪犯并放过
			else
			{
				close();
			}
		}
		
		private function addStamp():void
		{
			var stampStr:String;
			if (this.refjectFlag)
			{
				stampStr = "RejectStamp";
			}
			else
			{
				stampStr = "ApproveStamp";
			}
			var StampImage:Class = ResourceHelper.getInstance().getClassByName(stampStr);
			var stamp:Sprite = new StampImage();
			stamp.x = -100;
			stamp.y = -100;
			stamp.scaleX = 4;
			stamp.scaleY = 4;
			var targetScale:Number = 0.5;
			this.addChild(stamp);
			TweenLite.to(stamp, 0.8, {x:95, y:220, scaleX:targetScale, scaleY:targetScale, rotation: -10, ease:Expo.easeIn});
			
		}
		
		public function close():void
		{
			if (this.parent)
				this.parent.removeChild(this);
		}
		
	}
}